package cn.xiuxius.embedded.runtime.rtx51;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.util.Alarm;
import org.jetbrains.annotations.NotNull;

import com.intellij.openapi.util.Disposer;

public class TaskDocumentListener implements DocumentListener, Disposable {
    private final Document document;
    private final Alarm alarm;

    public TaskDocumentListener(@NotNull Document document) {
        this.document = document;
        Disposable disposable = Disposer.newDisposable();
        this.alarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, disposable);
        Disposer.register(disposable, this);
    }

    @Override
    public void documentChanged(@NotNull DocumentEvent event) {
        alarm.cancelAllRequests();
        alarm.addRequest(() -> ApplicationManager.getApplication().invokeLater(() -> {
            ApplicationManager.getApplication().runWriteAction(() -> {
                FileDocumentManager.getInstance().saveDocument(document);
            });
        }), 1000);
    }

    @Override
    public void dispose() {
        alarm.cancelAllRequests();
        document.removeDocumentListener(this);
    }
}


